<?

//Initiate Authenticate
SecurityRedirect ();
//error_reporting(E_ALL);


//initiate Vars
define("PRIMARY_KEY","lpj_id");
$FileName       = "ais_transaction_lpj.php";
$FileTemplate   = "ais_transaction_lpj_form.html";
$SubHeaderTitle = "Pertanggung Jawaban BS";
$TableName      = "tbllpj";
//$TableName_log      = "tbljoborder_log";
$HTMLFormName   = "LPJForm";
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
$created_by     = $_SESSION['AISUser'];


$MaxGrid        = "20";
$KTRASL                = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
//$FormFields    = array("lpj_id"=>"","lpj_code"=>"", "jo_id"=>"","jo_code"=>"","doc_ref"=>"","project_id"=>"","debtur"=>"","staff_id"=>"","operation_staff_id"=>"","jo_date"=>"date","rbt_idr"=>"","rbt_usd"=>"","rat_idr"=>"","rat_usd"=>"","jo_status"=>"","jo_appv_status"=>"");
$FormFields    = array("lpj_id"=>"","lpj_code"=>"", "jo_id"=>"","jo_code"=>"","doc_ref"=>"","project_id"=>"","debtur"=>"","staff_id"=>"","operation_staff_id"=>"","jo_date"=>"date","jo_appv_status"=>"");
buildsqlfield ("$TableName", $FormFields);


//Variable declaration
$lpj_id = GetParam("lpj_id","");
$jo_id = GetParam("jo_ido","");
$project_id = GetParam("project_id","");
$bl_no = GetParam("bl_no","");
$invoice_no = GetParam("invoice_no","");
$contract_deal = GetParam("contract_deal","");

//echo "$lpj_id"; exit;




$today = date("Y-m-d");
$strError = "";
$errorStatus = "";
$bl_status = "";
$inv_status = "";
$counter = "";

//End Variable declaration


//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name");
$FormCValue    = BuildHTMLField($FormFields,"value");
$FormHName     = BuildHTMLField($FormFields,"name",1);
$FormHValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************



if (trim(GetParam("form",""))==trim($HTMLFormName)) {
    if (GetParam("FormAction","")=="Save") {
           
                       
			if (trim(GetParam("lpj_id",""))=="AUTO NUMBERED BY SYSTEM")  
			{
				//echo "<pre>";
				//print_r($_POST);
				//echo "</pre>";
				//exit;
				//str_replace(",","",$value);
				
				$bspl_idr = str_replace(",","",GetParam("bspl_idr",""));
				$bsac_idr = str_replace(",","",GetParam("bsac_idr",""));
				$bsmg_idr = str_replace(",","",GetParam("bsmg_idr",""));
				
				//Fetch before insert
				 //$SQLLastProject1 = "SELECT * FROM tnllpj ORDER BY ".PRIMARY_KEY." DESC ";
				 //$ResultLastProject1  = $DBConnection->dbc->get_row($SQLLastProject1,ARRAY_A);            
				 //$LastProject1 = $ResultLastProject1["lpj_id"];
				$jo_date = GetParam("jo_date","");
				//list($day,$month,$year) = explode("/",GetParam("jo_date",""));
				//$jo_date  = "$year-$month-$day";
				//echo "$test"; exit;
				//$DBConnection->add_data($TableName,"jo_code",$jo_code_fix);
				$DBConnection->add_data($TableName,"lpj_code","LPJ");
				$DBConnection->add_data($TableName,"jo_id",GetParam("jo_ido",""));
				//$DBConnection->add_data($TableName,"jo_code",GetParam("jo_code",""));
				//$DBConnection->add_data($TableName,"contract_deal",$contract_deal);				
				//$DBConnection->add_data($TableName,"doc_ref",GetParam("doc_ref",""));
				//$DBConnection->add_data($TableName,"project_id",GetParam("project_id",""));
				//$DBConnection->add_data($TableName,"debtur",GetParam("debtur",""));
				//$DBConnection->add_data($TableName,"staff_id",GetParam("staff_id",""));
				//$DBConnection->add_data($TableName,"operation_staff_id",GetParam("operation_staff_id",""));
				//$DBConnection->add_data($TableName,"jo_date",$jo_date);  				
				//$DBConnection->add_data($TableName,"vessel",GetParam("vessel",""));
				//$DBConnection->add_data($TableName,"bl_no",GetParam("bl_no",""));
				//$DBConnection->add_data($TableName,"invoice_no",GetParam("invoice_no",""));
				$DBConnection->add_data($TableName,"bspl_idr",$bspl_idr);
				$DBConnection->add_data($TableName,"bsac_idr",$bsac_idr);
				$DBConnection->add_data($TableName,"bsmg_idr",$bsmg_idr);
				//$DBConnection->add_data($TableName,"rbt_idr",numberVal(GetParam("rbt_idr","")));
				//$DBConnection->add_data($TableName,"rbt_usd",numberVal(GetParam("rbt_usd","")));
				//$DBConnection->add_data($TableName,"rat_idr",numberVal(GetParam("rat_idr","")));
				//$DBConnection->add_data($TableName,"rat_usd",numberVal(GetParam("rat_usd","")));
				//$DBConnection->add_data($TableName,"created_by",$created_by);
				//$DBConnection->add_data($TableName,"jo_status",$resultStatus);
				//$DBConnection->add_data($TableName,"jo_appv_status",GetParam("jo_appv_status",""));

				$DBConnection->InsertGrid();
										
				//Fetch after insert
				
				
				//Update to Insert Jo Code             
				//$DBConnection->dbc->query("UPDATE tbljoborder set jo_code = '".$jo_code_fix."' WHERE jo_id = '".$LastProject2."'"); 
				//End Update           
				
				$SQLLastProject1 = "SELECT * FROM tbllpj ORDER BY ".PRIMARY_KEY." DESC ";
				$ResultLastProject1  = $DBConnection->dbc->get_row($SQLLastProject1,ARRAY_A);            
				$lpj_id = $ResultLastProject1["lpj_id"];
				
				FormSave("tbllpj_detail", "jumlah", array("adv_id"=>"","adv_code"=>"","adv_date"=>"","jumlah"=>"number","rupiah"=>"number"),array("lpj_id"=>$lpj_id),"lpj_detail_id");
				FormSave("tbllpjitem", "item_jumlah", array("item_jumlah"=>"number","item_remarks"=>""),array("lpj_id"=>$lpj_id),"item_id");				
				//$DBConnection->InsertGrid();
				
				$SQLCode = "SELECT max(lpj_code) from tbllpj";
				$ResultCode = $DBConnection->dbc->get_var($SQLCode);
				
				if ($ResultCode == "") {
					$ResultCode = 0;
					$counter = $ResultCode + 1; 
				} else {
					$ResultCode = substr($ResultCode, -3);
					$counter = ($ResultCode * 1) + 1; 
				}
				
				//$counter = $ResultCode + 1; 
				$counter = str_pad($counter, 3, "0", STR_PAD_LEFT);
				
				$ResultCode = "LPJ".$counter;
				
				$SQLUpdate = "UPDATE tbllpj SET lpj_code = '$ResultCode' WHERE lpj_id = $lpj_id";
				
				$DBConnection->dbc->query($SQLUpdate);
				//exit;
				//echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
				
				
				
				
				SetLogActivity($TransNo,"Create","");

			} 
			
			else 
			{
			    
				$DBConnection->dbc->query("DELETE FROM tbllpj_detail WHERE lpj_id='".$lpj_id."'");
				$DBConnection->dbc->query("DELETE FROM tbllpjitem WHERE lpj_id='".$lpj_id."'");

				//FormSave("tbljoactivity", "qty", array("jo_id"=>"","services_id"=>"","disburgement"=>"","qty"=>"","unit"=>"","curr"=>"","rate"=>"number","amount"=>"number","base_amount"=>"number","tax_rate"=>"","tax_amount"=>"number","tax_amount_usd"=>"number","total_amount"=>"number","total_amount_usd"=>"number","payment_status_id"=>"","dev_after_tax"=>"number","mul_after_tax"=>"number","nibt"=>"number","niat"=>"number", "bill_to" => ""),"","jo_id",$jo_id,"jo_log_id",$LastProject_log);
				//FormSave("tbljocargo", "cargo_type", array("jo_id"=>"","cargo_type"=>"","cargo_jumlah"=>"","cargo_pkgs"=>"","cargo_berat"=>"","cargo_volume"=>"","cargo_lamp"=>""),"","jo_id",$jo_id,"jo_log_id",$LastProject_log);
					
				FormSave("tbllpj_detail", "jumlah", array("adv_id"=>"","adv_code"=>"","adv_date"=>"","jumlah"=>"number","rupiah"=>"number"),array("lpj_id"=>$lpj_id),"lpj_detail_id");
				FormSave("tbllpjitem", "item_jumlah", array("item_jumlah"=>"number","item_remarks"=>""),array("lpj_id"=>$lpj_id),"item_id");																																									 
				$DBConnection->InsertGrid();
								   
				//$DBConnection->dbc->query("UPDATE ".$TableName." SET doc_ref='".GetParam("doc_ref","")."',contract_deal='".$contract_deal."',project_id='".GetParam("project_id","")."',debtur='".GetParam("debtur","")."',staff_id='".GetParam("staff_id","")."',operation_staff_id='".GetParam("operation_staff_id","")."',jo_date = '".$jo_date."',vessel='".GetParam("vessel","")."',rbt_idr = '".numberVal(GetParam("rbt_idr",""))."',rbt_usd = '".numberVal(GetParam("rbt_usd",""))."',rat_idr = '".numberVal(GetParam("rat_idr",""))."',rat_usd = '".numberVal(GetParam("rat_usd",""))."',jo_appv_status = '".GetParam("jo_appv_status","")."' WHERE jo_id='".$jo_id."'");
							
				SetLogActivity($TransNo,"Update","");
			}
				
		  
		  
		  if(!empty($strError))  		  
		  {
			 jsAlert($strError);	
		  }
          
		  
		  
          
          
          if($jo_id == "AUTO NUMBERED BY SYSTEM")
          {
			 $jo_redirect = $LastProject2;
		  }
		  
		  else
		  {
			 $jo_redirect = $jo_id;
		  }
		  
		  //exit();          
		  header("Location: $FileName?PageMode=Form&lpj_id=$lpj_id");
		  //redirectMeta($FileName."?PageMode=Form&jo_id=".$jo_redirect);
		  exit;

        
    }
    
    
    
}



//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";


//$VerifyFields = array("services_id1" => "Services","qty1" => "Quantity","unit1"=>"Unit","curr1"=>"Currency","rate1"=>"Rate");

$VerifyFields = array();
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar);


$InitFunction = "Masking();Masking2();";

$VerifyGrids = array();
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array(),"2");
$JSMasks  = $Masking1.$Masking2;
Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);



//************ SET FORM MODE ***************
$USER_CANPRINT_TAX="0";

if (GetParam(PRIMARY_KEY,"")) {
        $FormMode = "Edit";
        $USER_CANPRINT="1";
        $SQL ="SELECT vat FROM ais_memorial WHERE nobkt='".GetParam(PRIMARY_KEY,"")."' AND urut=999 ";
        if (strlen($DBConnection->dbc->get_var($SQL))) $USER_CANPRINT_TAX="1";
} else {
        $FormMode = "Add";
        $USER_CANPRINT="0";
}
//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY urut";
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************

//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Bank:
$SQLBank = "SELECT * FROM tblbank ORDER BY banknam";
//Select Kantor
$SQLKtr  = "SELECT * FROM tblkantor ORDER BY ktrasl";
//$SQLLocation = "SELECT * FROM $DBCoins.tblsubdepo ORDER BY sdname ";

$SQLUnit  = "SELECT  * FROM tblunit ORDER BY id";

$SQLPaymentStatus  = "SELECT  * FROM tbljopayment_status ORDER BY payment_status_id";

$SQLTaxRate  = "SELECT  * FROM tbltaxrate WHERE tax_group = 'revenue' ORDER BY tax_id";

$SQLCargoType  = "SELECT  * FROM tblcargotype ORDER BY cargo_id ASC";



//edited by Adit van Smith



//GET Kurs

$SQLGetKurs = "SELECT * FROM ais_kurssi WHERE curr = 'USD' ORDER BY tglbkt DESC";
$ResultGetKurs  = $DBConnection->dbc->get_row($SQLGetKurs,ARRAY_A);   

$kursUSD = $ResultGetKurs['rate'];


$SQLGetKursTax = "SELECT * FROM ais_kurspjk WHERE curr = 'USD' ORDER BY tglbkt DESC";
$ResultGetKursTax  = $DBConnection->dbc->get_row($SQLGetKursTax,ARRAY_A);   

$kursUSDTax = $ResultGetKursTax['rate'];

//END GET Kurs



//Project Get Header

if(GetParam(PRIMARY_KEY,"") != '' && GetParam(PRIMARY_KEY,"") != 'AUTO NUMBERED BY SYSTEM')
{
   $SQLProject = "SELECT a.*,b.*,c.*,d.*,e.*,f.nama as operation_staff_name FROM ".$TableName." as a
                  JOIN tbljoborder as b on a.jo_id = b.jo_id
                  JOIN tbldebtur as c on b.debtur = c.CUCODE 
                  LEFT JOIN ".$DBGeneral.".tblstaff as d on b.staff_id = d.staff_id 
                  JOIN tblproject as e ON b.project_id = e.project_id 
				  				LEFT JOIN ".$DBGeneral.".tblstaff as f on b.operation_staff_id = f.staff_id
                  WHERE a.".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY a.".PRIMARY_KEY." ASC";

   $ResultProject  = $DBConnection->dbc->get_results($SQLProject,ARRAY_A);   
   
   
   if($ResultProject[0]['contract_deal'] == '1')
   {
	  $check_contract = "checked";   
   }
   
   else
   {
	  $check_contract = "";   
   }
   
   

}

else
{
   $ResultProject  = array(	
      array(

         "jo_id" => "",
         "jo_code" => "",
         "doc_ref" => "",
         "project_id" => "",
         "debtur" => "",
         "staff_id" =>"",
		 "operation_staff_id" =>"",
         "jo_date" =>$today,
         "bl_no" => "",
         "invoice_no" => "",
         "vessel" => "",
         "rbt_idr" =>"",
         "rbt_usd" =>"",
         "rat_idr" =>"",
         "rat_usd" =>"",
         "jo_appv_status" =>""

      )
   );
   
   $check_contract = "";
   
   //SELECT * FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'Foo'

}


//Project



$HeaderFields = array("jo_id"=>"","jo_code"=>"","project_id"=>"project_id","debtur"=>"debtur","staff_id"=>"staff_id","operation_staff_id"=>"","jo_date"=>"date","rbt_idr"=>"","rbt_usd"=>"","rat_idr"=>"","rat_usd"=>"","jo_appv_status" => "");

//Leave Here Untouch
$FormHName     = BuildHTMLField($HeaderFields,"name",1);
$FormHValue    = BuildHTMLField($HeaderFields,"value",1);

$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";


if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= " WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."' AND urut=999 ";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);

//Edited by Adit van Smith
$SQLCustomer = "SELECT * FROM ".$DBGeneral.".tbldebitur ORDER BY CUNAME ASC";
//End Edited by Adit van Smith

$SQLgetProject = "SELECT * FROM tblproject WHERE assign_to_project = 'assigned' ORDER BY project_name ASC";


// HTML Value
$TBS->MergeBlock("headbln",$FormHName);
$TBS->MergeBlock("headblv",$ResultProject);
$TBS->MergeBlock("dayblk",GetArrayDay());
$TBS->MergeBlock("project",$DBMysql,$SQLgetProject);

$TBS->MergeBlock("customer",$DBMysql,$SQLCustomer);
$TBS->MergeBlock("unit",$DBMysql,$SQLUnit);
$TBS->MergeBlock("paymentStatus",$DBMysql,$SQLPaymentStatus);
$TBS->MergeBlock("taxRate",$DBMysql,$SQLTaxRate);
$TBS->MergeBlock("CargoType",$DBMysql,$SQLCargoType);



//********************************* HTML GRID *********************************************
//HTML Grid

/*$SQLGrid = "SELECT * FROM tbljoactivity as a
            LEFT JOIN tblservices as b on a.services_id = b.services_id 
            LEFT JOIN tbldebtur as c on a.bill_to = c.CUDEBTUR_FIN 
            WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY a.act_id";*/

$SQLGrid = "SELECT * FROM tbllpj_detail as a 
						JOIN tbllpj b ON a.lpj_id = b.lpj_id
						JOIN ais_advance c ON a.adv_id = c.adv_id 
            WHERE a.".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY a.lpj_detail_id";
$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);



$SQLGridItem = "SELECT * FROM tbllpjitem as a
				JOIN tbllpj b ON a.lpj_id = b.lpj_id
				JOIN tblactivity_setup c ON a.item_id = c.act_nr_id
                WHERE a.".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY a.item_id";

//echo "$SQLGridItem";
$ResultItem  = $DBConnection->dbc->get_results($SQLGridItem,ARRAY_A);
$ResultItem  = BuildEmptyGrid ($FormFields, $MaxGrid, $ResultItem);

$TBS->MergeBlock("blgItem",$ResultItem);
$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************


function redirectMeta($url)
{
	echo "Redirecting.... Please Wait.....";
	echo "<meta http-equiv='refresh' content='0;url=".$url."'>";
}

function jsAlert($msg)
{
	$msg = str_replace("\n","\\n",$msg);
	
	echo '<script>
	      alert("'.$msg.'");	
	      </script>';
}


function checkBL($bl_no,$checkStat="")
{
	global $DBConnection;	
	$errorStatus = "";
	
	if($bl_no != "")
	{
		if(!empty($checkStat))
		{
		   $SQLCheckBL = "SELECT COUNT(bl_no) as jml_bl FROM tbljoborder WHERE bl_no = '".$bl_no."' AND bl_status = '' ";
		}
		else
		{
		   $SQLCheckBL = "SELECT COUNT(bl_no) as jml_bl FROM tbljoborder WHERE bl_no = '".$bl_no."' ";	
		}
		
		$ResultCheckBL  = $DBConnection->dbc->get_results($SQLCheckBL,ARRAY_A);
	   
		$jml_bl = intval($ResultCheckBL[0]['jml_bl']);
	   
		if($jml_bl > 0)
		{
		   $errorStatus = "yes";
		}
		
		else
		{
		   $errorStatus = "";
		}
    }
    
    return $errorStatus;
    
}



function checkInv($invoice_no,$checkStat="")
{
	global $DBConnection;
	
     if(!empty($checkStat))
	 {
         $SQLCheckInv = "SELECT COUNT(invoice_no) as jml_inv FROM tbljoborder WHERE invoice_no = '".$invoice_no."' AND inv_status = '' ";
     }
     else
     {
		 $SQLCheckInv = "SELECT COUNT(invoice_no) as jml_inv FROM tbljoborder WHERE invoice_no = '".$invoice_no."' ";
	 }
          
     $ResultCheckInv  = $DBConnection->dbc->get_results($SQLCheckInv,ARRAY_A);
     
     $jml_inv = intval($ResultCheckInv[0]['jml_inv']);
			
     if($jml_inv > 0)
     {
	     $errorStatus = "yes";
     }
   
    
     else
     {
	     $errorStatus = "";
	 }
    
     return $errorStatus;
    
}

function checkBLInvStat($jo_id)
{
	global $DBConnection;
	
    $SQLCheck = "SELECT count(jo_id) as jml FROM tbljoborder WHERE jo_id = '".$jo_id."' AND bl_status = 'approved' AND inv_status = 'approved' ";
    
    $ResultCheck  = $DBConnection->dbc->get_results($SQLCheck,ARRAY_A);
   
    $jml = intval($ResultCheckBL[0]['jml']);
   
    if($jml > 0)
    {
	   $bl_inv_status = "approved";
    }
    
    else
    {
	   $bl_inv_status = "";
	}
    
    return $bl_inv_status;
    
}



function FormInsert() {
        global $DBConnection,$FileName;
        $DBConnection->Insert();
        header("Location: $FileName?PageMode=Form");
        exit;
}

function FormUpdate() {
        global $DBConnection;
        $DBConnection->Update();
}

function FormDelete() {
        global $DBConnection,$FileName,$TableName;
        $DBConnection->deleteGrid("$TableName","nobkt");
        header("Location: $FileName");
        exit;
}

function FormSearch () {

}

function FormCancel () {
        global $FileName;
        header("Location: ".$FileName."?PageMode=List");
        exit;
}




function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey="", $PrimaryKeyVal="",$PrimaryKey_log="", $PrimaryKeyVal_log="") {
        global $FileName, $MaxGrid, $DBConnection;
        $TotalData = $MaxGrid * 2;
        $NewDataStart = GetParam("NewData","0");
        $NewDataStart = 1;

          

        for ($a=1;$a<=$MaxGrid;$a++) {
	    //Begin For

            
            if (GetParam($keyField.$a,""))
            {
			//Begin Check if Empty Keyfield	
            
                 
                foreach ($FormFields as $key=>$formatting) {

                         //need advice
                         /*if (!GetParam($keyField.$a,"")) {
                                print GetParam($keyField.$a,"");
                                $EndOfData = 1;
                                break;
                         }*/
                         //need advice

                        if(!empty($PrimaryKey))
                        {
                            $value = GetParam($key.$a,"");
														
														$adv_id = GetParam("adv_id".$a,"");
														$SQLAdv = "UPDATE ais_advance SET bs_progress = 'lpj' WHERE adv_id = $adv_id";
														$DBConnection->dbc->query($SQLAdv);
														
                            if ($formatting=="number") $value = str_replace(",","",$value);
                            if ($formatting=="date")
                            {
                                    list($day,$month,$year) = explode("/",$value);
                                    $value = "$year-$month-$day";
                            }

                            $DBConnection->add_data($table,$key,$value);

                        }

                }

                $rate = StrToNumber(GetParam("rate",""));
                $jmh  = StrToNumber(GetParam("jumlah".$a,""));

                // Add by Chandra (15 May 2009)
                $cash_type = GetParam("cash_type","");
                //var_dump($cash_type); exit;



                if($cash_type) $DBConnection->add_data($table,'cash_type',$cash_type);
                // end update


                if (strlen($SpecialCase)) 
                {
                        foreach ($SpecialCase as $key => $value) 
                        {
                                //print "add_data($table,$key,$value);<br>";
                                $DBConnection->add_data($table,$key,$value);
                        }
                }

//                print "$a < $NewDataStart<br>";
                if ($a < $NewDataStart) 
                {
                         if (strlen($PrimaryKey)) 
                         {
                            $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
                         } 
                         else 
                         {
                            $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
                         }
                } 
                
                else 
                {
                        $DBConnection->InsertGrid();
//                        $DBConnection->dbc->debug();
                }
            
            
            //End Check if Empty Keyfield
            }
            
            
        //End For    
        }
        $DBConnection->ClearData();
}


//*************** USER FUNCTION *******************

function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        foreach ($arrayfield as $key=>$Formatting) {
            $value = GetParam($key,"");
            if ($Formatting=="date") {
                list($day,$month,$year) = explode("/",$value);
                $value = "$year-$month-$day";
            } elseif ($Formatting=="number") $value = str_replace(",","",$value);
            $DBConnection->add_htmlfield($table,$key,$value);
        }
}


function DeleteRecord ($sequence_name,$PageSize) {
        global $DBConnection,$FileName,$TableName;
        for ($x=1;$x<=$PageSize;$x++) {
                if (GetParam($sequence_name.$x,""))        {
                        $DBConnection->deleteGrid("$TableName","memorial_id",$sequence_name.$x);
            }
        }
}

function BuildFields ($FormFields) {
                global $DBConnection;
                $str = "";
                foreach ($FormFields as $key=>$formatting) {
                        if (strlen($str)) $str .= ",$key";
                        else $str = "$key";
                }
                return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
                global $DBConnection;
                $array_fields = array();
                for ($x=0;$x<$MaxGrid;$x++) {
                        foreach ($FormFields as $key=>$formatting){
                                $a=$x+1;
                                $array_fields[$key.$a] = "$formatting";
                        }
                }
                return $array_fields;
}

function FlushCustomer ($TableName, $tmp) {
        global $DBConnection;

        if ($tmp) $TEMPORARY = "TEMPORARY";
        $DBC = new mydb(DB_USER, DB_PASSWORD, DB_NAME2, DB_HOST);

        $SQL = "SELECT kodecustomer,nama,cr_term,kdtype FROM customer ";
        if (GetParam("kdtype","")) $SQL .= " WHERE kdtype='".GetParam("kdtype","")."'";
        $MyResult = $DBC->dbc->get_results($SQL,ARRAY_N);
        if (!$MyResult) return false;
         $session_file = substr(md5(time()), 0, 8);
           $session_file = "/tmp/".$session_file.".tmp";
        BufferToFile ($MyResult,$session_file);

        $DBConnection = new mydb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
        $SQL = "DROP TABLE IF EXISTS `$TableName`;";
        $DBConnection->dbc->query($SQL);

        $SQL= "CREATE $TEMPORARY TABLE `$TableName` (
                          `kodecustomer` varchar(20) NOT NULL default '',
                          `nama` varchar(50) default NULL,
                          `cr_term` int(4) default NULL,
                          `kdtype` varchar(20) default NULL
                          )";
        $DBConnection->dbc->query($SQL);

           $SQL = "LOAD DATA INFILE '$session_file' INTO TABLE $TableName FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'";
        $DBConnection->dbc->query($SQL);
        unlink($session_file);
        return true;
}

function GetLastDateReport() {
        global $DBConnection;
        list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
        $current_date = "$year-$month-$day";

    $SQL = "DELETE FROM ais_piutang_sisa WHERE aging_date>='$current_date' ";
    if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
    if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";
    $DBConnection->dbc->query($SQL);
    //$DBConnection->dbc->debug();

        $SQL = "SELECT max(aging_date) FROM ais_piutang_sisa WHERE aging_date<='$current_date' ";
        if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";

        return $DBConnection->dbc->get_var($SQL);
}

function convert_code($code,$digit)
{
		
	$length = strlen($code);	
	$tot_str = $digit - $length;	
	$code_edit = "";
	
	for($i=0;$i < $tot_str; $i++)
	{
		$code_edit.= "0";
	}
	
	$code_edit.= $code;
	
	return $code_edit;
	
}


function numberVal($val)
{
	$value = str_replace(",","",$val);
	return $value;
}



?>
